<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>拉框放大与缩小</title>
    <link rel="stylesheet" href="./css/ol.css">
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <style media="screen">
      html, body, div.map {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
      }
      .x-zoom-icons {
        position: absolute;
        left: 0.5em;
        top: 5em;
        z-index: 999;
      }
      .x-zoom-icons span{
        display: block;
        padding: 7px;
        cursor: pointer;
        border: 1.5px solid rgba(255, 255, 255, 0.5);
        border-radius: 5px;
        background-color: rgb(255, 255, 255);
      }
      .ol-dragzoom {
        border: 3px dashed rgb(255, 0, 0);
        border-radius: 3px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map">
      <div class="x-zoom-icons">
        <span id="zoom_in" class="glyphicon glyphicon-zoom-in"></span>
        <span id="zoom_out" class="glyphicon glyphicon-zoom-out"></span>
      </div>
    </div>

    <script src="./js/ol.js" charset="utf-8"></script>
    <script type="text/javascript">
      var dragzoomActive = false;

      var map = new ol.Map({
        target: "map",
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.transform([108, 39], 'EPSG:4326', 'EPSG:3857'),
          zoom: 11
        })
      });

      // 初始化一个拉框控件
      var dragZoom = new ol.interaction.DragZoom({
        condition: ol.events.condition.always,
        out: false, // 此处为设置拉框完成时放大还是缩小
      });
      map.addInteraction(dragZoom);
      dragZoom.setActive(false);

      // 绑定放大缩小按钮事件
      document.querySelector("#zoom_in").addEventListener('click', function() {
        if (dragzoomActive) {
          dragZoom.setActive(false);
          dragzoomActive = false;
          document.querySelector("#map").style.cursor = "default";
        } else {
          dragZoom.G = false;
          dragZoom.setActive(true);
          dragzoomActive = true;
          document.querySelector("#map").style.cursor = "crosshair";
        }
      }, false);
      document.querySelector("#zoom_out").addEventListener('click', function() {
        if (dragzoomActive) {
          dragZoom.setActive(false);
          dragzoomActive = false;
          document.querySelector("#map").style.cursor = "default";
        } else {
          dragZoom.G = true;
          dragZoom.setActive(true);
          dragzoomActive = true;
          document.querySelector("#map").style.cursor = "crosshair";
        }
      }, false);

    </script>
  </body>
</html>
